package com.hub.nio.socket.nio;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ author 令狐冲
 * @ date & time 2025/1/24 14:35
 */
public class FileReadWriteExample {

    public static void main(String[] args) throws FileNotFoundException {
        try (RandomAccessFile file = new RandomAccessFile("test.txt", "rw")) {
            FileChannel channel = file.getChannel();
            String content = "Hello, Java NIO!";
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put(content.getBytes());
            byteBuffer.flip(); // 切换到读模式
            channel.write(byteBuffer);

        } catch (Exception e) {

        } finally {

        }


        try (FileInputStream is = new FileInputStream("test.txt");) {
            FileChannel channel = is.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(16);
            //用channel将数据读到buffer中
            channel.read(buffer);
            System.out.println(new String(buffer.array()));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
